<template>
	<view class="bench">
		<view class="bench-header">
			<view class="bench-header_tabs u-flex">
				<view class="u-flex-1">
					<uni-segmented :current="current" :values="tabs" activeColor="#0089FF" @clickItem="tabChange" />
				</view>
				<view class="bench-search_btn" @click="$goPage('/search',{current:current})">
					<u-icon name="search" color="#B9BFC5" size="56"></u-icon>
				</view>
			</view>
		</view>
		<scroll-view class="demand" scroll-y v-if="current == 0" @scrolltolower="getList">
			<view class="demand-content">
				<view class="demand-item" v-for="(item, index) in demandLists" :key="index"
					@click="$goPage('/demand/detail', { dkey: item.Dkey })">
					<view class="demand-item_header u-flex">
						<text class="demand-item_title u-flex-1">{{ item.NickName }}</text>
						<text class="demand-item_state">{{ item.StatText == '完工'? '开航':item.StatText}}</text>
					</view>
					<view class="demand-item_cnt">{{ item.Content }}</view>
					<view class="article-images" v-if="item.ImgPackJson1 != ''">
						<template v-for="(img, index) in item.ImgPackJson1">
							<reply-images-item :item="img" :index="index" :imgjson="item.ImgPackJson1"></reply-images-item>
						</template>
					</view>
					<view class="demand-item_time">{{ item.AddTimeText }}</view>
				</view>
				<u-loadmore :status="demandStatus" :icon-type="iconType" :load-text="loadText" margin-bottom="45"
					margin-top="45" color="#C1C0C0" />
			</view>
		</scroll-view>
		<view class="repair-content" v-else>
			<view class="repair-tabs">
				<u-tabs :list="repairTabs" :is-scroll="false" v-model="tab" @change="repairTabChange"></u-tabs>
			</view>
			<scroll-view scroll-y @scrolltolower="downGetList" style="height: 100%"  refresher-enabled="true" :refresher-triggered="isTriggered"  @refresherrefresh="topGetList">
				<view class="repair-item" v-for="(item, index) in repairLists" :key="index"
					@click="$goPage('/staff/bench/detail', { project: item.Pid, discount:item.Discount})">
					<view class="repair-item_cell u-flex">
						<view class="u-flex-1">
							<i class="icon u-m-r-20 u-m-l-10 extend-icon-color" :class="item.isExtend ? 'icon-xiangxia1': 'icon-xiangyou'"
							@click.stop="item.isExtend = !item.isExtend"></i>
							<text class="repair-item_cell--label">项目名称：</text>
							<text class="repair-item_cell--value">{{ item.ProjectName }}</text>
						</view>
						<view class="repair-item_cell--state">
							<text class="icon icon-lunchuan"></text>
							{{ item.StatText }}
						</view>
					</view>
					<view v-show="item.isExtend" class="u-m-l-60 u-m-t-16">
						<view class="repair-item_cell">
							<text class="repair-item_cell--label">顾客公司：</text>
							<text class="repair-item_cell--value">{{item.CorpName != "" ? item.CorpName : "-"}}</text>
						</view>
						<view class="repair-item_cell" v-if="item.StatText != '开航' &&tab != 1
            ">
							<text class="repair-item_cell--label">联系人：</text>
							<text class="repair-item_cell--value">{{
              item.LinkerName != "" ? item.LinkerName : "-"
            }}</text>
						</view>
						<view class="repair-item_cell" v-if="tab == 1 || tab == 2">
							<text class="repair-item_cell--label">机务：</text>
							<text class="repair-item_cell--value">{{
                item.MaintenanceStaffName != "" ? item.MaintenanceStaffName : "-"
              }}</text>
						</view>
						<view class="repair-item_cell" v-if="tab == 0">
							<text class="repair-item_cell--label">收单日期：</text>
							<text class="repair-item_cell--value">{{
                item.ReceiveDateText != "" ? item.ReceiveDateText : "-"
              }}</text>
						</view>
						<view class="repair-item_cell" v-if=" tab == 0">
							<text class="repair-item_cell--label">预计修理日期：</text>
							<text class="repair-item_cell--value">{{
                item.PreFixDateText != "" ? item.PreFixDateText : "-"
              }}</text>
						</view>
						<view class="repair-item_cell" v-if="item.StatText == '合同洽谈' || item.StatText == '报价'">
							<text class="repair-item_cell--label">当前报价：</text>
							<text class="repair-item_cell--value">{{
                item.CurrentAmountText != "" ? (item.Discount == 0 ? item.CurrentAmountText : (parseFloat(item.CurrentAmountText.replace(/[,]/g,""))*(100-item.Discount)/100)) : "-"
              }}</text>
						</view>
						<view class="repair-item_cell" v-if=" item.StatText == '合同洽谈' || item.StatText == '报价'">
							<text class="repair-item_cell--label">当前工期：</text>
							<text class="repair-item_cell--value">{{
                item.PreFixPeriod != "" ? item.PreFixPeriod : "-"
              }}</text>
						</view>
						<view class="repair-item_cell" v-if="(item.StatText == '合同签订' || tab == 1 || tab == 2) && item.PermissionPrice == 1">
							<text class="repair-item_cell--label">合同金额：</text>
							<text class="repair-item_cell--value">{{
              item.ContractFee != "" ? item.ContractFee : "-"
            }}</text>
						</view>
						<view class="repair-item_cell" v-if="item.StatText == '合同签订' || tab == 1 || tab == 2">
							<text class="repair-item_cell--label">合同工期：</text>
							<text class="repair-item_cell--value">{{
              item.ContractPeriod != "" ? item.ContractPeriod : "-"
            }}</text>
						</view>
						<view class="repair-item_cell"
							v-if="item.StatText == '开工' || item.StatText == '进厂' || item.StatText == '进坞' || item.StatText == '再次进坞' || item.StatText == '出坞' || item.StatText == '再次出坞' || item.StatText == '完工'">
							<text class="repair-item_cell--label">待报价行数：</text>
							<text class="repair-item_cell--value">{{
					      item.PriceRow != "" ? item.PriceRow : "-"
					    }}</text>
						</view>
						<view class="repair-item_cell"
							v-if="(item.StatText == '进厂' || item.StatText == '开工' || item.StatText == '进坞'|| item.StatText == '再次进坞' || item.StatText == '出坞' || item.StatText == '再次出坞' || item.StatText == '完工') && item.PermissionPrice == 1 && item.PermissionContract == 1">
							<text class="repair-item_cell--label">当前金额：</text>
							<text class="repair-item_cell--value">{{
              item.CurrentAmountText != "" ?  (item.Discount == 0 ? item.CurrentAmountText : (parseFloat(item.CurrentAmountText.replace(/[,]/g,""))*(100-item.Discount)/100)): "-"
            }}</text>
						</view>
						<view class="repair-item_cell"
							v-if="item.StatText == '进厂' || item.StatText == '开工' || item.StatText == '进坞'|| item.StatText == '再次进坞' || item.StatText == '出坞' || item.StatText == '再次出坞' || item.StatText == '完工'">
							<text class="repair-item_cell--label">已开工天数：</text>
							<text class="repair-item_cell--value">{{
                item.StartPeriod != "" ? item.StartPeriod : "-"
              }}</text>
						</view>
						<view class="repair-item_cell"
							v-if="item.StatText == '进厂' || item.StatText == '开工' || item.StatText == '进坞'|| item.StatText == '再次进坞' || item.StatText == '出坞' || item.StatText == '再次出坞' || item.StatText == '完工'">
							<text class="repair-item_cell--label">预计完工日期：</text>
							<text class="repair-item_cell--value">{{
              item.PreDoneDateText != "" ? item.PreDoneDateText : "-"
            }}</text>
						</view>
						<!-- <view class="repair-item_cell" v-if=" item.StatText == '开航'">
						<text class="repair-item_cell--label">结算金额：</text>
						<text class="repair-item_cell--value">{{
                item.ContractSettlementText != "" ? item.ContractSettlementText : "-"
              }}</text>
					</view> -->
						<view class="repair-item_cell" v-if=" item.StatText == '开航'">
							<text class="repair-item_cell--label">实际工期：</text>
							<text class="repair-item_cell--value">{{
                item.EndPeriod != "" ? item.EndPeriod : "-"
              }}</text>
						</view>
						<view class="repair-item_cell" v-if=" item.StatText == '开航'">
							<text class="repair-item_cell--label">完工日期：</text>
							<text class="repair-item_cell--value">{{
                item.EndDateText != "" ? item.EndDateText : "-"
              }}</text>
						</view>
						<view class="repair-item_cell" v-if=" tab == 1 || tab == 2">
							<text class="repair-item_cell--label">修理船厂：</text>
							<text class="repair-item_cell--value">{{
              item.ShipYard != "" ? item.ShipYard : "-"
            }}</text>
						</view>
						<view class="repair-item_cell" v-if=" tab == 4">
							<text class="repair-item_cell--label">未达成日期：</text>
							<text class="repair-item_cell--value">{{
                item.CancelDateText != "" ? item.CancelDateText : "-"
              }}</text>
						</view>
						<view class="repair-item_cell" v-if=" tab == 3 || tab == 4">
							<text class="repair-item_cell--label">所属部门：</text>
							<text class="repair-item_cell--value">{{item.DeptName != "" ? item.DeptName : "-"}}</text>
						</view>
					</view>
				</view>
				<u-loadmore :status="status" :icon-type="iconType" :load-text="loadText" margin-bottom="45"
					margin-top="45" color="#C1C0C0" />
			</scroll-view>
		</view>

	</view>
</template>

<script>
	import replyImagesItem from '@/components/reply-images-item/index.vue';
	import uniSegmented from "@/components/uni-segmented-control/uni-segmented-control.vue";
	import pageMixin from '@/utils/tabBarMixin';
	import homeStorage from "@/utils/storage.js";
	export default {
		mixins: [pageMixin],
		data() {
			return {
				tabs: ['需求', '修理'],
				tab: 2,
				current: 1,
				demandLists: [],

				repairTabs: [{
						name: '修理前'
					},
					{
						name: '已签约'
					}, {
						name: '修理中'
					}, {
						name: ' 已完成'
					}, {
						name: ' 未达成'
					},
					// {
					// 	name: '合同签订'
					// },
				],
				repairLists: [],
				demandQuery: {
					idx: 1,
					size: 10
				},
				query: {
					type: 2,
					idx: 1,
					size: 10
				},
				query2:{
					type: 2,
					idx: 0,
					size: 10,
					page:1,
				},
				demandStatus: 'loading',
				status: 'loading',
				iconType: 'flower',
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '到底了哦'
				},
				flag: true,
				isTriggered : false,
			}
		},
		onLoad() {
			this.$store.commit('checkUserLogin');
			uni.setStorageSync('type', this.tab)
			this.getRepairLists();
		},
		onShow() {},
		components: {
			uniSegmented,
			replyImagesItem
		},
		computed: {},
		methods: {
			getList() {

				let {
					demandQuery,
					demandStatus
				} = this;

				if (demandStatus == 'nomore') {
					return;
				}
				return this.$http.get('/staff/biz/demand/list', {
					userType:this.$store.state.vuex_user.type,
					...demandQuery
				}).then(res => {
					let {
						idx,
						size
					} = demandQuery;
					this.demandLists = idx <= 1 ? res : JSON.parse(JSON.stringify(this.demandLists)).concat(res);
					this.demandQuery.idx = res.length < size ? idx : idx + 1;
					this.demandStatus = res.length < size ? 'nomore' : 'loading';
				})
			},
			// GOEASY
/* 			connectGoEasy() {
				uni.showLoading();
				this.goEasy.connect({
					id: this.vuex_user.uid,
					data: {
						name: this.vuex_user.uname,
						avatar: this.vuex_user.avatar
					},
					onSuccess: () => {
						console.log('GoEasy connect successfully.')
					},
					onFailed: (error) => {
						console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error
							.content);
					},
					onProgress: (attempts) => {
						console.log('GoEasy is connecting', attempts);
					}
				});

				//订阅Goeasy消息
				this.goEasy.pubsub.subscribe({
					channel: "user" + this.vuex_user.uid,
					onMessage: function(message) {
						console.log("Channel:" + message.channel + " content:" +
							message.content);
					},
					onSuccess: function() {
						console.log("Channel订阅成功。");
					},
					onFailed: function(error) {
						console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" +
							error.content)
					}
				});
			}, */
			async getRepairLists() {
				let {
					idx,
					size
				} = this.query;
				let networkType = await this.getNetWork();
				if (networkType == 'none') {
					//如果 是断网的情况下获取store 里面的数据放入LISTS
					let data = await this.getLocalCacheList();
					if(data.length / size <  idx){
						if(data.length == size * ( idx - 1 )){
								this.status = 'nomore';
						}else{
							for(var i =  size * ( idx - 1) ; i < data.length-1 ;i++){
								this.repairLists.push( data[i])
							}
								this.status = 'nomore';
						}
					}else{
						for(var i =  size * ( idx - 1) ;i <  size * idx ; i++){
							this.repairLists.push( data[i])
						}
						//55大于50 加一 如果等于 50  不加
						this.query.idx += 1 ;
						this.status = 'loading';
					}
					this.flag = true
					this.isTriggered = false
				}else{
					//每次全量获取前端分页显示,分为两个LIST一个LIST存分页  另一个取后面全部都取出来放到store中从第二次开始 所有数据都从store中获取
					//计算store中一共有X页X条
					if(	this.query.idx == 1 ){
						//先取分页数据 接下来取全部数据
						this.$http.get('/mgr/biz/project/pager/data', this.query).then(res => {
							this.repairLists = res
							JSON.parse(JSON.stringify(this.repairLists)).forEach((item, index) => {
								this.getPermissionPrice(item.Pid, index)
								this.getPermissionContract(item.Pid, index)
								item.isExtend = false
							})
							this.query.idx = res.length < size ? idx : idx + 1;
							this.status = res.length < size ? 'nomore' : 'loading';
							this.flag = true
							this.isTriggered = false
						})
						this.query2.type = this.query.type
						this.$http.get('/mgr/biz/project/pager/data', this.query2).then(res => {
							//取全部的数据
							let list = res
							list.forEach((item, index) => {
								this.getPermissionPrice(item.Pid, index)
								this.getPermissionContract(item.Pid, index)
								item.isExtend = false
							})
							this.saveLocalCacheTopic(list, true);
						})
					}else{
						//如果翻了下一页那么从store中获取数据
						let data =await this.getLocalCacheList();
						// console.log(data,JSON.stringify(data))
						//计算可以循环几次如果数size次或者this.query.size 次
						//判断是否是最后一页数据如果  5.5<6是最后一页
						if(data.length / size <  idx){
							if(data.length == size * ( idx - 1 )){
									this.status = 'nomore';
							}else{
								for(var i =  size * ( idx - 1) ; i < data.length-1 ;i++){
									this.repairLists.push( data[i])
								}
									this.status = 'nomore';
							}
						}else{
							for(var i =  size * ( idx - 1) ;i <  size * idx ; i++){
								this.repairLists.push( data[i])
							}
							//55大于50 加一 如果等于 50  不加
							this.query.idx += 1 ;
							this.status = 'loading';
						}
						this.flag = true
					}
				}
			},
			//封装一个异步返回方法用来判断是否有网络
			getNetWork(){
				return new Promise((resolve,reject)=>{
					const start = Date.now()
					let net = ''
						uni.getNetworkType({
							success: function(res) {
								net = res.networkType
							},
						});
					resolve(net)
				})
			},
			topGetList(){
				if (!this.isTriggered) {
					this.isTriggered = true
				}
				this.query.idx=1
				this.getRepairLists();	
			},
			downGetList(){
				if(this.status == 'nomore') return 
				this.getRepairLists()
			},
			async getLocalCacheList() {
				let data = await this.getStorageTopic();
				return data;
			},
			async getStorageTopic() {
				let res = await homeStorage.getDataNew({
					key: 'server_project_list_' + this.query.type,
					page:true
				});
				return res;
			},
			async saveLocalCacheTopic(data, isBefore) {
				homeStorage.insertNew([...data], isBefore, 'server_project_list_'+this.query.type, false)
			},
			getPermissionPrice(proj,index) {
				this.$http.get('/client/biz/project/item/permission/price', {
					project: proj
				}).then(res => {
					this.repairLists[index].PermissionPrice = res;
					// console.log('是否有报价权限',res)
				});
			},
			getPermissionContract(proj,index) {
				let that = this;
				that.$http.get('/client/biz/project/item/permission/contract', {
					project: proj
				}).then(res => {
					this.repairLists[index].PermissionContract = res;
				});
			},
			tabChange(e) {
				this.current = e.currentIndex;
				if (e.currentIndex == 0) {
					this.demandLists = [];
					this.demandStatus = 'loading';
					this.demandQuery.idx = 1;
					return this.getList()
				} else {
					this.repairLists = [];
					this.status = 'loading';
					this.query.idx = 1;
					this.query.type = 2;
					return this.getRepairLists();
				}
			},
			format(num){
				 let str = num.toString();
				 let leg = str.length;
				 let arr = str.split('');
				 if(leg <= 3) return str;
				 for (let i = leg - 3; i > 0; i-=3) {
				   arr.splice(i, 0, ',')
				 }
				 return arr.join('')+ '.000';
			},
			repairTabChange(index) {
				this.tab = index;
				uni.setStorageSync('type', this.tab)
				this.status = 'loading';
				this.query.idx = 1;
				this.query.type = 1;
				this.repairLists = [];
				this.query.order = 'dept_no ASC, stat_time ASC';
				if (index == 1) {
					this.query.type = 6;
					this.query.order = 'dept_no ASC, stat_time ASC';
				}
				if (index == 2) {
					this.query.type = 2;
					this.query.order = 'dept_no ASC, stat_time ASC';
				}
				if (index == 3) {
					this.query.type = 3;
					this.query.order = 'stat_time DESC';
				}
				if (index == 4) {
					this.query.type = 4;
					this.query.order = 'stat_time DESC';
				}
				if (index == 5) {
					this.query.type = 5;
					this.query.order = 'stat_time DESC';
				}
				this.getRepairLists();
			},
			onPullDownRefresh() {
				this.tabChange({
					currentIndex: this.current
				}).then(() => {
					uni.stopPullDownRefresh();
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.article-images {
		clear:both;
		overflow: hidden;
		padding: 0 0 10rpx 10rpx;
		display: flex;
		flex-wrap: wrap;
	}
	.bench {
		height: 100vh;
		padding-top: 130rpx;
		//   white-space: normal;
		//   word-break: break-all;
	}

	.bench-header {
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
		padding-top: 0;
		background-color: #ffffff;
	}

	.bench-header_tabs {
		width: 400rpx;
		padding: 30rpx 0;
		margin: 0 auto;
	}

	.bench-search_btn {
		position: absolute;
		right: 30rpx;
	}

	.demand {
		height: 100%;
		box-sizing: border-box;
		padding: 20rpx 30rpx;
		background-color: #ffffff;

		&-item {
			background-color: #f3f3f3;
			padding: 20rpx;
			margin-bottom: 20rpx;
			border-radius: 10rpx;
			color: #444444;

			&_header {
				padding-bottom: 20rpx;
				border-bottom: 1rpx solid rgba(210, 210, 210, 0.5);

				.demand-item_state {
					color: #131313;
				}
			}

			&_cnt {
				margin: 30rpx 0;
				line-height: 44rpx;
			}

			&_title {
				font-weight: 600;
			}

			&_time {
				text-align: right;
			}
		}
	}

	.demand-content {
		overflow: hidden;
	}

	.repair-content {
		height: 100%;
		box-sizing: border-box;
		padding-top: 96rpx;
	}

	.repair-tabs {
		width: 100%;
		padding: 0 60rpx;
		background-color: #ffffff;
		border-top: 1rpx solid #f7f7f7;
		position: fixed;
		top: 124rpx;
		left: 0;
		z-index: 99;
	}

	.repair-item {
		padding: 36rpx 36rpx 36rpx 24rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
    .extend-icon-color {
			color: #577A9E; 
		}
		&_cell {
			&+& {
				margin-top: 24rpx;
			}

			&--label {
				color: #666666;
			}

			&--value {
				color: #000000;
			}

			&--state {
				position: relative;
				right: -30rpx;
				height: 58rpx;
				line-height: 58rpx;
				padding: 0 14rpx;
				font-size: 28rpx;
				color: #5e6d82;
				background-color: #ecf8ff;

				.icon {
					margin-right: 6rpx;
				}
			}

			&--state:before {
				content: "";
				position: absolute;
				left: -20rpx;
				top: 0;
				width: 0;
				height: 0;
				border-top: 29rpx solid transparent;
				border-bottom: 29rpx solid transparent;
				border-right: 29rpx solid #ecf8ff;
			}
		}
	}
</style>
